﻿using Secs4Net;
using Secs4Net.Sml;
using SimulateSECSDevice;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SECSDevice
{
    internal class SecsLogger : ISecsGemLogger
    {
        readonly RichTextBox rtbLog;

        internal SecsLogger(RichTextBox rtb)
        {
            this.rtbLog = rtb;
        }

        public void MessageIn(SecsMessage msg, int id)
        {
            rtbLog.Invoke((MethodInvoker)delegate
            {
                rtbLog.SelectionColor = Color.Black;
                rtbLog.AppendText($"<-- [0x{id:X8}] {msg.ToSml()}\n");
            });
        }

        public void MessageOut(SecsMessage msg, int id)
        {
            rtbLog.Invoke((MethodInvoker)
                delegate
                {
                    rtbLog.SelectionColor = Color.Black;
                    rtbLog.AppendText($"--> [0x{id:X8}] {msg.ToSml()}\n");
                }
            );
        }

        public void Info(string msg)
        {
            rtbLog.Invoke((MethodInvoker)delegate
            {
                rtbLog.SelectionColor = Color.Blue;
                rtbLog.AppendText($"{msg}\n");
            });
        }

        public void Warn(string msg)
        {
            rtbLog.Invoke((MethodInvoker)delegate
            {
                rtbLog.SelectionColor = Color.Green;
                rtbLog.AppendText($"{msg}\n");
            });
        }

        public void Error(string msg, SecsMessage? message, Exception? ex)
        {
            rtbLog.Invoke((MethodInvoker)delegate
            {
                rtbLog.SelectionColor = Color.Red;
                rtbLog.AppendText($"{msg}\n");
                rtbLog.AppendText($"{message?.ToSml()}\n");
                rtbLog.SelectionColor = Color.Gray;
                rtbLog.AppendText($"{ex}\n");
            });
        }

        public void Debug(string msg)
        {
            rtbLog.Invoke((MethodInvoker)delegate
            {
                rtbLog.SelectionColor = Color.Yellow;
                rtbLog.AppendText($"{msg}\n");
            });
        }
    }
}
